<?php

namespace Admin\Controller;

use Zend\Form\Annotation\AnnotationBuilder;
use Admin\Controller\IndexController;
use Admin\Form\SearchForm;
use Admin\Model\DBO\SearchBookDBO;

class SearchDocumentController extends IndexController {

    public $form;

    public function getForm() {
        if (!$this->form) {
            $cataloging = new SearchForm();
            $builder = new AnnotationBuilder();
            $this->form = $builder->createForm($cataloging);
            $this->form->get('keySearch')->setOptions(
                    array(
                        'value_options' => array(
                            '0' => 'Tìm trong',
                            '1' => 'Mã tài liệu',
                            '2' => 'Tên tài liệu',
                            '3' => 'Tên tác gả',
                            '4' => 'Nhà xuất bản',
                        ),
                    )
            );
        }

        return $this->form;
    }

    function Replace_TiengViet($str) {

        $str = preg_replace("/(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/i", 'a', $str);

        $str = preg_replace("/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/i", 'e', $str);

        $str = preg_replace("/(ì|í|ị|ỉ|ĩ)/i", 'i', $str);

        $str = preg_replace("/(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/i", 'o', $str);

        $str = preg_replace("/(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/i", 'u', $str);

        $str = preg_replace("/(ỳ|ý|ỵ|ỷ|ỹ)/i", 'y', $str);

        $str = preg_replace("/(đ)/i", 'd', $str);



        $str = preg_replace("/(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)/", 'A', $str);

        $str = preg_replace("/(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/", 'E', $str);

        $str = preg_replace("/(Ì|Í|Ị|Ỉ|Ĩ)/", 'I', $str);

        $str = preg_replace("/(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)/", 'O', $str);

        $str = preg_replace("/(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/", 'U', $str);

        $str = preg_replace("/(Ỳ|Ý|Ỵ|Ỷ|Ỹ)/", 'Y', $str);

        $str = preg_replace("/(Đ)/", 'D', $str);

        //$str = str_replace(" ", "-", str_replace("&*#39;","",$str)); 
        // sử dụng cho ai có mục đích rewriteURL 

        return $str;
    }

    public function checkRole() {
        $roleId = $this->getRole();
        // 3 la quyen thu thu: chi co the cho phep ban doc muon trã tài liệu
        if ($roleId == 3) {
            $this->redirect()->toRoute('success/default', array('action' => 'errorRole'));
        }
    }

    public function indexAction() {
        // kiem tra neu chua dang nhap thi quay ve lai trang dang nhap
        $this->checkRole3();
        // Neu dang nhap roi thi hien thi len sach sach nguoi dung
        // Lay thuc the dang nhap dua ra layout
        $this->layout()->identity = $this->getAuthService()->getIdentity();
        $form = $this->getForm();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $myMessage = array();
            $result = null;
            $allAuthor = array();
            $dataRequest = $request->getPost();
            $form->setData($dataRequest);
            if ($form->isValid()) {
                $data = $form->getData();
                $keySearch = $data['keySearch'];
                $valueSearch = $data['valueSearch'];
                if ($keySearch == 1) {
                    // Tim theo ma tai lieu
                    $this->redirect()->toRoute('search-document/default', array('action' => 'searchBookBarcode', 'id' => $valueSearch));
                } else if ($keySearch == 2) {
                    // Tim theo ten tai lieu
                    $filter = new \Zend\I18n\Filter\Alpha(true);
                    $filter2 = new \Zend\Filter\Word\SeparatorToSeparator();
                    $valueSearch = $filter->filter($valueSearch);
                    $valueSearch = $filter2->filter($valueSearch);
                    $valueSearch = $this->Replace_TiengViet($valueSearch);
                    $this->redirect()->toRoute('search-document/default', array('action' => 'searchBookName', 'id' => $valueSearch));
                } else if ($keySearch == 3) {
                    //  Tim theo ten tac gia
                    $filter = new \Zend\I18n\Filter\Alpha(true);
                    $filter2 = new \Zend\Filter\Word\SeparatorToSeparator();
                    $valueSearch = $filter->filter($valueSearch);
                    $valueSearch = $filter2->filter($valueSearch);
                    $valueSearch = $this->Replace_TiengViet($valueSearch);
                    $this->redirect()->toRoute('search-document/default', array('action' => 'searchBookAuthor', 'id' => $valueSearch));
                    $this->searchBookAuthor($valueSearch);
                } else if ($keySearch == 4) {
                    // Tim theo nha xuat ban
                    //    $this->searchPublisher($valueSearch);
                } else {
                    // ban chua nhap du thong tin tim kiem
                    $myMessage['inputError'] = 'inputError';
                }
            } else {
                foreach ($form->getMessages() as $value => $ms) {
                    $myMessage[$value] = $value;
                }
            }
        }
        return array(
            'form' => $form,
        );
    }

    public function searchBookNameAction() {
        // Kiểm tra đăng nhập
        // kiem tra neu chua dang nhap thi quay ve lai trang dang nhap
        $this->checkRole3();
        $form = $this->getForm();
        $valueSearch = $this->params()->fromRoute('id', 0);
        $filter = new \Zend\Filter\Word\SeparatorToSeparator('-', ' ');
        $valueSearch = $filter->filter($valueSearch);
        $objectSearchBook = new SearchBookDBO($this->getServiceLocator());
        $resultSet = $objectSearchBook->searchBookName($valueSearch);
        // Tim kiem them ma tac gia
        $allAuthor = null;
        $myMessage = array();
        foreach ($resultSet as $key) {
            $bookBarcode = $key['bookBarcode'];
            $authors = $objectSearchBook->searchBookAuthor($bookBarcode);
            $i = 1;
            $tmp = array();
            foreach ($authors as $author) {
                $tmp[$i++] = $author['author'];
            }
            $allAuthor[$bookBarcode] = $tmp;
        }
        $paginator = null;
        if (isset($bookBarcode) && $bookBarcode != null) {
            $iteratorAdapter = new \Zend\Paginator\Adapter\Iterator($objectSearchBook->searchBookName($valueSearch));
            $paginator = new \Zend\Paginator\Paginator($iteratorAdapter);
            $paginator->setCurrentPageNumber((int) $this->params()->fromQuery('page', 1));
            $paginator->setItemCountPerPage(7);
            $paginator->setPageRange(5);
            // set the number of items per page to 10
        }
        if ($paginator == null) {
            $myMessage['notFoundResult'] = 'notFoundResult';
        }
        return array(
            'form' => $form,
            'myMessage' => $myMessage,
            'paginator' => $paginator,
            'allAuthor' => $allAuthor,
        );
    }

    public function searchBookBarcodeAction() {
        // Kiểm tra đăng nhập
        // kiem tra neu chua dang nhap thi quay ve lai trang dang nhap
        $this->checkRole3();
        $form = $this->getForm();
        $valueSearch = $this->params()->fromRoute('id', 0);
        $bookBarcode = (int) $valueSearch;
        if ($bookBarcode == 0) {
            $filter = new \Zend\Filter\Word\SeparatorToSeparator('-', ' ');
            $filter2 = new \Zend\Filter\Digits();
            $valueSearch = $filter->filter($valueSearch);
            $bookBarcode = $filter2->filter($valueSearch);
        }
        $objectSearchBook = new SearchBookDBO($this->getServiceLocator());
        $resultSet = $objectSearchBook->searchBookBarcode($bookBarcode);
        // Tim kiem them ma tac gia
        $allAuthor = null;
        $myMessage = array();
        foreach ($resultSet as $key) {
            $bookBarcode = $key['bookBarcode'];
            $authors = $objectSearchBook->searchBookAuthor($bookBarcode);
            $i = 1;
            $tmp = array();
            foreach ($authors as $author) {
                $tmp[$i++] = $author['author'];
            }
            $allAuthor[$bookBarcode] = $tmp;
        }
        $paginator = null;
        if (isset($bookBarcode) && $bookBarcode != null) {
            $iteratorAdapter = new \Zend\Paginator\Adapter\Iterator($objectSearchBook->searchBookBarcode($bookBarcode));
            $paginator = new \Zend\Paginator\Paginator($iteratorAdapter);
            $paginator->setCurrentPageNumber((int) $this->params()->fromQuery('page', 1));
            $paginator->setItemCountPerPage(7);
            $paginator->setPageRange(5);
            // set the number of items per page to 10
        }
        if ($paginator == null) {
            $myMessage['notFoundResult'] = 'notFoundResult';
        }
        return array(
            'form' => $form,
            'myMessage' => $myMessage,
            'paginator' => $paginator,
            'allAuthor' => $allAuthor,
        );
    }

    public function searchBookAuthorAction() {
        // Kiem tra đăng nhập
        // kiem tra neu chua dang nhap thi quay ve lai trang dang nhap
        $this->checkRole3();
        $form = $this->getForm();
        $valueSearch = $this->params()->fromRoute('id', 0);
        $filter = new \Zend\Filter\Word\SeparatorToSeparator('-', ' ');
        $valueSearch = $filter->filter($valueSearch);
        $objectSearchBook = new SearchBookDBO($this->getServiceLocator());
        $resultSet = $objectSearchBook->searchBookAuthor($valueSearch);
        $allAuthor = null;
        $myMessage = array();
        foreach ($resultSet as $key) {
            $bookBarcode = $key['bookBarcode'];
            $authors = $objectSearchBook->searchBookAuthor($bookBarcode);
            $i = 1;
            $tmp = array();
            foreach ($authors as $author) {
                $tmp[$i++] = $author['author'];
            }
            $allAuthor[$bookBarcode] = $tmp;
        }
        $paginator = null;
        if (isset($bookBarcode) && $bookBarcode != null) {
            $iteratorAdapter = new \Zend\Paginator\Adapter\Iterator($objectSearchBook->searchBookAuthor($valueSearch));
            $paginator = new \Zend\Paginator\Paginator($iteratorAdapter);
            $paginator->setCurrentPageNumber((int) $this->params()->fromQuery('page', 1));
            $paginator->setItemCountPerPage(7);
            $paginator->setPageRange(5);
            // set the number of items per page to 10
        }
        if ($paginator == null) {
            $myMessage['notFoundResult'] = 'notFoundResult';
        }
        return array(
            'form' => $form,
            'myMessage' => $myMessage,
            'paginator' => $paginator,
            'allAuthor' => $allAuthor,
        );
    }

}